package com.heima.comment.interceptor;

import com.heima.common.exception.CustomException;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.common.UserThreadLocalUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class CommentInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String userId = request.getHeader("userId");
        //2.判断是否是登录
        if(request.getRequestURI().contains("/login")){
            //放行
            return true;
        }
        if (StringUtils.isBlank(userId)){
            throw new CustomException(AppHttpCodeEnum.NEED_LOGIN);
        }
        ApUser apUser = new ApUser();
        apUser.setId(Integer.parseInt(userId));
        UserThreadLocalUtil.setUser(apUser);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserThreadLocalUtil.clear();
    }
}
